package com.glkj.vipsystem.plugin.message;

import cn.hutool.core.date.DateUtil;
import com.glkj.vipsystem.common.utils.Constant;
import com.glkj.vipsystem.entity.ao.MemberAO;
import com.glkj.vipsystem.entity.ao.OrderAO;
import com.glkj.vipsystem.entity.ao.VipCardAO;
import com.glkj.vipsystem.service.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * 微信消息推送工具类，推送不多，直接写了
 */
@Component
@Slf4j
public class MessageBuilder {

    @Resource
    private WxMpService wxMpService;
    @Resource
    private IOrderService orderService;
    @Resource
    private IMemberService memberService;
    @Resource
    private IVipCardService vipCardService;
    @Resource
    private IVipCardRecordService vipCardRecordService;
    @Resource
    private IShopService shopService;

    /**
     * 收银成功给用户发送消费通知
     *
     * @param orderId 订单id
     */
    public void buildCashMessage(Long orderId) {
        if (orderId == null) return;
        // 启用线程进行推送
        Executors.newSingleThreadExecutor().execute(() -> {
            OrderAO orderAO = orderService.selectById(orderId);
            if (orderAO == null || orderAO.getVipCardId() == null) return;
            Integer memberId = orderAO.getMemberId();
            if (memberId == null) return;
            MemberAO memberAO = memberService.selectById(memberId);
            if (memberAO == null || memberAO.getOpenid() == null) return;
            VipCardAO vipCardAO = vipCardService.selectById(orderAO.getVipCardId());
            if (vipCardAO == null) return;

            String cashTime = DateUtil.format(orderAO.getCreateTime(), "yyyy-MM-dd HH:mm");
            String shopName = orderAO.getShopName();

            // 构建推送消息
            WxMpTemplateMsgService templateMsgService = wxMpService.getTemplateMsgService();
            WxMpTemplateMessage message = new WxMpTemplateMessage();

            // 根据卡类型构建推送消息
            List<WxMpTemplateData> data = new ArrayList<>();
            if (vipCardAO.getCardType() == Constant.VipCardType.CIKA.getValue()) {
                // 模板id
                message.setTemplateId(MessageTemplate.CashCiKa.getId());
                data.add(new WxMpTemplateData("first", "尊敬的会员，您的次卡已成功消费"));
                // 模板数据
                data.add(new WxMpTemplateData("keyword1", cashTime));
                data.add(new WxMpTemplateData("keyword2", shopName));
                data.add(new WxMpTemplateData("keyword3", "1"));
                data.add(new WxMpTemplateData("keyword4", vipCardAO.getCardTimes() + ""));
            } else if (vipCardAO.getCardType() == Constant.VipCardType.CHONGZHIKA.getValue()) {
                // 模板id
                message.setTemplateId(MessageTemplate.CashChongzhi.getId());
                data.add(new WxMpTemplateData("first", "尊敬的会员，您的充值卡已成功消费"));
                // 模板数据
                data.add(new WxMpTemplateData("keyword1", orderAO.getOrderAmount().toPlainString()));
                data.add(new WxMpTemplateData("keyword2", shopName));
                data.add(new WxMpTemplateData("keyword3", vipCardAO.getCardBalance().toPlainString()));
            } else if (vipCardAO.getCardType() == Constant.VipCardType.JIFENKA.getValue()) {
                // 模板id
                message.setTemplateId(MessageTemplate.CashJifen.getId());
                data.add(new WxMpTemplateData("first", "尊敬的会员，您的积分卡已成功消费"));
                // 模板数据
                data.add(new WxMpTemplateData("keyword1", cashTime));
                data.add(new WxMpTemplateData("keyword2", orderAO.getOrderAmount().toPlainString()));
                data.add(new WxMpTemplateData("keyword3", orderAO.getPointsCost().toString()));
                data.add(new WxMpTemplateData("keyword4", "积分消费"));
                data.add(new WxMpTemplateData("keyword5", vipCardAO.getCardPoints() + ""));
            }

            data.add(new WxMpTemplateData("remark", "如有疑问，请联系我们！"));
            message.setData(data);

            // 推送
            message.setToUser(memberAO.getOpenid());
            try {
                templateMsgService.sendTemplateMsg(message);
            } catch (WxErrorException e) {
                WxError error = e.getError();
                log.error("微信推送消息失败:errorCode:{},errorMsg:{}", error.getErrorCode(), error.getErrorMsg());
            }
        });
    }

}
